package cn.tellsea.auth.security.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Jwt 工具类
 *
 * @author Tellsea
 * @date 2023/8/8
 */
@Component
@RequiredArgsConstructor
public class JwtTokenUtils {

    private final RedisTemplate<String, String> redisTemplate;
    @Value("${tellsea.auth.security.jwt.secret}")
    private String secret;
    @Value("${tellsea.auth.security.jwt.expiration}")
    private long expiration;

    /**
     * 生成令牌
     *
     * @param username
     * @return
     */
    public String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析令牌
     *
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    /**
     * 验证令牌
     *
     * @param token
     * @param username
     * @return
     */
    public boolean validateToken(String token, String username) {
        String cachedToken = redisTemplate.opsForValue().get(username);
        return token.equals(cachedToken) && !isTokenExpired(token);
    }

    /**
     * 判断令牌是否过期
     *
     * @param token
     * @return
     */
    public boolean isTokenExpired(String token) {
        Date expirationDate = getExpirationDateFromToken(token);
        return expirationDate.before(new Date());
    }

    /**
     * 从令牌中获取过期时间
     *
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims.getExpiration();
    }

    /**
     * 缓存令牌到Redis
     *
     * @param token
     * @param username
     */
    public void cacheToken(String token, String username) {
        redisTemplate.opsForValue().set(username, token, expiration, TimeUnit.MILLISECONDS);
    }

    /**
     * 从Redis中删除令牌
     *
     * @param username
     */
    public void deleteToken(String username) {
        redisTemplate.delete(username);
    }
}
